/* eslint-disable guard-for-in */
/* eslint-disable no-restricted-syntax */
//
// layoutComposer.js：线路页面组件
//

import {
  Layout as LayoutDHX,
  Toolbar as ToolbarDHX,
  Chart as ChartDHX,
} from 'dhx-suite-package';
import Raphael from 'raphael';
import { Message, Alert } from '@/components/message';
import simulationModule from '@/store/module/simulation';
import gateModule from '@/store/module/gate';
import { QCircuit } from './QCircuit';

const QComposer = ({
  barHeight: 37,

  // 0. 整体布局（三行）
  layoutContainer: null,

  // 1. 工具栏
  toolbarCircuit: null,

  // 2. 线路可视化
  qcircuit: null, // QCircuit类的实例
  layoutCircuit: null,
  canvasCircuit: null,

  // 3. 结果可视化
  layoutMeasure: null,
  chartMeasure: null,

  // ///////////////////////////////////////
  init() {
    // 0. 整体布局（三行）///////////////
    this.layoutContainer = this.layoutContainer_create();
    this.layoutContainer_event();

    // 1. 工具栏
    this.toolbarCircuit = this.toolbarCircuit_create();
    this.toolbarCircuit_event();

    // 2. 线路可视化
    this.layoutCircuit = this.layoutCircuit_create();
    this.layoutCircuit_reload();

    // 3. 结果可视化
    this.layoutMeasure = this.layoutMeasure_create();
    this.layoutMeasure_reload(); // 创建chart

    // 挂载各组件 /////////////////////////
    this.layoutContainer.getCell('toolbarContainer').attach(this.toolbarCircuit);
    this.layoutContainer.getCell('circuitContainer').attach(this.layoutCircuit);
    this.layoutContainer.getCell('measureContainer').attach(this.layoutMeasure);
    // 挂载chart
    this.layoutMeasure.getCell('chartMeasure').attach(this.chartMeasure);

    return this.layoutContainer;
  },

  // ///////////////////////////////////////
  // 0. 整体布局
  // ///////////////////////////////////////
  layoutContainer_create() {
    const mylayout = new LayoutDHX('layoutContainer', {
      type: 'line',
      rows: [
        {
          id: 'toolbarContainer',
          height: this.barHeight,
        }, {
          id: 'circuitContainer',
          height: '60%',
          resizable: true,
        }, {
          id: 'measureContainer',
          header: '输出概率（小端输出）',
          height: '40%',
          resizable: true,
        },
      ],
    });
    return mylayout;
  },
  layoutContainer_event() {
    const that = this;
    const myevents = that.layoutContainer.events;
    myevents.on('afterResizeEnd', (/* id */) => { // TODO：改变面板和结果的大小
      // console.log('composer', id);
      // var size = that.layoutContainer.getCell("visualContainer").getSize();
      // console.log(size);
    });
  },
  // ///////////////////////////////////////
  // 1. 工具栏
  // ///////////////////////////////////////
  toolbarCircuit_create() {
    const mytoolbar = new ToolbarDHX('toolbar', {
      css: 'toolbar_style',
      navigationType: 'pointer',
      data: [
        {
          id: 'add',
          html: '<i class="fa-solid fa-plus"></i>',
          tooltip: '增加量子比特',
        }, {
          id: 'color',
          html: '<i class="fa-solid fa-palette"></i>',
          tooltip: '修改颜色',
        }, {
          type: 'spacer',
        }, {
          id: 'simulator',
          type: 'selectButton',
          value: 'Python模拟器',
          items: [
            {
              id: 'simulator1',
              value: 'Python模拟器',
            },
          ],
        }, {
          id: 'run',
          type: 'button',
          html: '<i class="fa-solid fa-play"></i> 运行线路',
          tooltip: '运行线路',
          twoState: false,
          circle: true,
          css: 'toolbar_btn_style',
        },
      ],
    });
    return mytoolbar;
  },
  toolbarCircuit_event() {
    const that = this;
    const myevents = that.toolbarCircuit.events;
    myevents.on('click', (id) => {
      switch (id) {
        case 'add':
          that.qcircuit.addQubit();
          break;
        case 'color':
          that.qcircuit.colorpicker.show();
          break;
        case 'run':
          that.simulate(); // 向后端提交任务请求
          break;
        default: break;
      }
    });
  },

  // ///////////////////////////////////////
  // 2. 线路可视化
  // ///////////////////////////////////////
  layoutCircuit_create() {
    const mylayout = new LayoutDHX(null, {
      type: 'none',
      cols: [
        {
          id: 'circuit',
          width: '100%',
        },
      ],
    });
    return mylayout;
  },
  layoutCircuit_reload() { // 定时检查线路容器是否加载完成
    const that = this;
    // console.log('layoutCircuit_reload');
    that.layoutCircuit.getCell('circuit').attachHTML('<div class="unselectable" id="circuit"></div>');
    let circuit = document.querySelector('#circuit');
    if (circuit) {
      that.circuit_reload(); // 加载线路
    } else {
      const checkCircuit = setInterval(() => {
        circuit = document.querySelector('#circuit');
        if (circuit) {
          clearInterval(checkCircuit); // 清空定时器
          that.circuit_reload(); // 加载线路
        }
      }, 100);
    }
  },
  circuit_reload(circuit = null) { // 刷新线路
    const that = this;
    if (that.canvasCircuit == null) { // 新建画布
      that.canvasCircuit = new Raphael('circuit', 1200, 600);
    }
    // 加载量子门并生成线路
    that.glistbasic(circuit);
  },

  // ///////////////////////////////////////
  // 3. 结果可视化
  // ///////////////////////////////////////
  layoutMeasure_create() {
    const mylayout = new LayoutDHX('layoutMeasure', {
      type: 'none',
      cols: [
        {
          id: 'chartMeasure',
          html: '<div id="chart"></div>',
          css: 'chart_style',
        },
      ],
    });
    return mylayout;
  },
  // layoutMeasure_event() {},
  layoutMeasure_reload() { // 定时检查返回chart容器是否加载完成
    const that = this;
    let measure = document.querySelector('#chart');
    if (measure) {
      that.chartMeasure = that.chartMeasure_create(); // 创建chart
    } else {
      const check = setInterval(() => {
        measure = document.querySelector('#chart');
        if (measure) {
          clearInterval(check); // 清空定时器
          that.chartMeasure = that.chartMeasure_create();
        }
      }, 100);
    }
  },

  chartMeasure_create() {
    const mychart = new ChartDHX(null, {
      type: 'bar',
      scales: {
        bottom: {
          text: 'state',
        },
        left: {
          maxTicks: 10,
          // max: 100,
          min: 0,
          textTemplate(prob) {
            return `${prob}%`;
          },
        },
      },
      series: [
        {
          id: 'prob',
          value: 'prob',
          color: '#5E83BA',
          fill: '#5E83BA',
        },
      ],
      data: [
        { state: '0', prob: 0 },
        { state: '1', prob: 0 },
      ],
    });
    return mychart;
  },

  chartMeasure_reload(data) {
    const that = this;
    const prob = [];
    const keys = Object.keys(data).sort();
    for (let i = 0; i < keys.length; i++) {
      prob.push({ state: keys[i], prob: data[keys[i]] });
    }
    that.chartMeasure.data.parse(prob);
  },

  // ///////////////////////////////////////
  // 4. 后端
  // ///////////////////////////////////////
  simulate() { // 线路 => 模拟
    const that = this;
    // 获取线路抽象，把只有基础的gate和oracle
    const qcircuitJson = that.qcircuit.getCircuit();
    simulationModule.actions.simulate(null, qcircuitJson) // 模拟线路
      .then((res) => {
        const { prob } = res.data.data;
        console.log('prob', prob);
        that.chartMeasure_reload(prob);
        Message('模拟成功');
      }).catch((err) => {
        console.log('simulate err', err);
        Alert(err.response.data.msg);
      });
  },
  // 从数据库中加载所有的gate
  glistbasic(circuit) {
    const that = this;
    gateModule.actions.glistbasic()
      .then((res) => {
        const basicGates = res.data.data.gates;
        that.qcircuit = new QCircuit(that.canvasCircuit, circuit, basicGates); // 新建线路
      }).catch((err) => {
        console.log('glistbasic err', err);
        Alert(err.response.data.msg);
      });
  },
});

export default QComposer;
